<template>
  <!-- 未采用&产品发布页面 -->
  <view class="create-product h-full flex flex-col box-border">
    <div class="overflow-auto flex-1 p-32rpx" style="min-height: 0;">
      <up-form :labelWidth="70" class="create-product-card-info" :rules="rules" labelPosition="top" :model="formData"
        ref="infoFormRef">
        <up-form-item label="产品名称" prop="productName">
          <up-input v-model="formData.name" :maxlength="50" placeholder="请输入"></up-input>
        </up-form-item>
        <up-form-item label="产品价格" prop="productPrice">
          <view class="flex items-center">
            <view class="w-200rpx mr-10rpx"> <up-input class="w-100rpx mr-10rpx" v-model="formData.currency" disabled
                disabledColor="#ffffff" border="surround" suffixIcon="arrow-down" @tap="showCurrency = true"></up-input>
            </view>
            <up-input type="number" v-model="formData.productPrice" placeholder="请输入产品价格" count
              @change="priceChange(formData.productPrice)">
            </up-input>
          </view>
        </up-form-item>
        <up-form-item label="产品重量" prop="weight">
          <up-input type="number" v-model="formData.weight" placeholder="请输入" count>
            <template #prefix>g</template>
          </up-input>
        </up-form-item>
        <up-form-item :labelWidth="110" label="商家SKU编码" prop="supplierSkuId">
          <up-input v-model="formData.supplierSkuId" :maxlength="50" placeholder="如没有可不填"></up-input>
        </up-form-item>
        <up-form-item label="OEM编码" :labelWidth="110" labelPosition="top" prop="oemCode">
          <view class="oem-box" @click="show = true">
            <view class="p-10rpx text-coolgray" v-if="!oemCode?.length">请输入，如有多个用逗号隔开</view>
            <view class="p-10rpx" v-for="(code, idx) in oemCode" :key="idx">{{ code }}</view>
          </view>
          <up-textarea v-if="false" :height="88" :maxlength="1500" placeholder="请输入，如有多个用逗号隔开" @change="onVaildFile"
            @blur="onVaildFile" @click="show = true, isFocus = true"></up-textarea>
        </up-form-item>
        <up-form-item labelPosition="top" label="物品照片" prop="files">
          <up-upload :fileList="formData.files" name="files" multiple :maxCount="3"
            :uploadText="`可上传${3 - formData.files.length}张图片`" @after-read="afterRead" @delete="deleteFile" />
        </up-form-item>
      </up-form>
    </div>
    <view class="foot-card flex justify-center items-center w-full h-144rpx p-32rpx box-border">
      <up-button color="#1A5FA9" type="primary" shape="circle" :text="productId ? '确认编辑' : '确认发布'"
        @click="addProductSave()"></up-button>
    </view>

  </view>
  <!-- 货币选择弹窗 -->
  <up-picker :show="showCurrency" :columns="[currencyList]" keyName="unitSymbol" @confirm="currencyChange"
    @cancel="showCurrency = false">
  </up-picker>
  <!-- oem弹窗 -->
  <up-popup :show="show" @close="show = false" @open="show = true">
    <view class="create-product flex flex-col">
      <view class="p-32rpx">
        <up-form :labelWidth="70" class="oem-form" labelPosition="top" :labelStyle="{ fontWeight: 900 }"
          :model="formData" ref="oemFormRef">
          <up-form-item label="OEM编码" :labelWidth="110" labelPosition="top" prop="oemCode">
            <up-textarea ref="oemRef" v-model="formData.oemCode" :height="88" :maxlength="1500" :focus="isFocus"
              placeholder="请输入，如有多个用逗号隔开"></up-textarea>
          </up-form-item>
        </up-form>
      </view>
      <view class="foot-card flex justify-center items-center w-full h-144rpx p-32rpx box-border">
        <view class="mr-24rpx w-50%">
          <up-button shape="circle" text="取消" @click="cancelOem"></up-button>
        </view>
        <view class="w-50%">
          <up-button color="#1A5FA9" type="primary" shape="circle" text="保存" @click="saveOem()"></up-button>
        </view>
      </view>
    </view>
  </up-popup>
</template>

<script setup lang="ts">
import { handleFile } from "@/api/request"
import { productManageSupSaveProduct } from '@/genapi/_product'
import { productManageSupUpdateProduct } from '@/genapi/_product'
import { productQueryProductDetailId } from '@/genapi/_productDetail'
import { thousandSeparatFormat, deThousandSeparatFormat } from "@/utils/utils";
import { useSupplierStore } from '@/store/index'

import { debounce } from '@antfu/utils'
const infoFormRef = ref()
const productId = ref('')
const show = ref(false)
const showCurrency = ref(false)
const isFocus = ref(false)
const oemCode = ref<string[]>([])
const currentRecord = ref({})
const deleteImgIds = ref<any[]>([])
const formData = reactive({
  name: '',
  productPrice: '',
  weight: '',
  oemCode: '',
  supplierSkuId: '',
  files: [] as any,
  currency: '',
  currencyCode: ''
})
const rules = reactive({
  productPrice: [
    {
      validator: (rule: any, value: any, cb: (val?: string) => void) => {
        if (!value) {
          cb('请输入产品价格')
        } else {
          cb()
        }
      },
      trigger: ['change', 'blur'],
    }
  ],
  oemCode:
  {
    validator: (rule: any, value: any, cb: (val?: any) => void) => {
      if (!formData.files.length && !formData.oemCode?.length) {
        cb(new Error('OEM号和图片至少传一个'))
      }
      else { cb() }
    },
    trigger: ['change', 'blur'],
  },
  files:
  {
    validator: (rule: any, value: any, cb: (val?: any) => void) => {
      if (!formData.files.length && !formData.oemCode) {
        cb(new Error('OEM号和图片至少传一个'))
      }
      else { cb() }
    },
    trigger: ['change', 'blur'],
  }
})

const supplierStore = useSupplierStore()
const currencyList = computed(() => supplierStore.supplierInfo.currencyList)
const includeRMB = computed(() => currencyList.value.some((item: any) => item.code === 'CNY'))
function close() {
  show.value = false
  isFocus.value = false
  onVaildOem()
  onVaildFile()
}
function currencyChange(e: any) {
  formData.currency = e.value[0].unitSymbol
  formData.currencyCode = e.value[0].code
  showCurrency.value = false
}
// 保存oem
function saveOem() {
  if (formData.oemCode.trim()) {
    const tempArr = formData.oemCode.split(/[,，\n]/g)
    const repeatOemArr: string[] = []
    const oemArr: string[] = []
    tempArr.forEach((item: string) => {
      if (oemArr.includes(item)) {
        if (!repeatOemArr.includes(item)) {
          repeatOemArr.push(item)
        }
      } else
        oemArr.push(item)
      return item
    })
    if (repeatOemArr.length) {
      uni.showToast({
        title: `${repeatOemArr.join()}OEM重复，已自动去重`,
        icon: 'none'
      })
      formData.oemCode = oemArr.join()
    }
    oemCode.value = oemArr
  } else {
    oemCode.value = []
  }
  close()
}
// 取消输入oem
function cancelOem() {
  formData.oemCode = oemCode.value.join()
  close()
}
// oem修改时图片校验必填
function onVaildFile() {
  if (formData.oemCode) {
    infoFormRef.value.clearValidate('files')
  } else {
    infoFormRef?.value?.validateField('files')
  }
}
// oem校验必填
function onVaildOem() {
  infoFormRef?.value?.validateField('oemCode')
}
const uploadFilePromise = (url, params) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${import.meta.env.VITE_BASE_API_URL}/api/productManageSup/uploadProductFile`,
      filePath: url,
      name: 'files',
      header: {
        Authorization: 'Bearer ' + uni.getStorageSync('token')
      },
      formData: params,
      success: (res) => {
        resolve(res.data || true)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}
// 删除文件
function deleteFile(event: any) {
  formData.files.splice(event.index, 1)
  infoFormRef?.value?.validateField('files')
  infoFormRef?.value?.validateField('oemCode')
  if (event.file?.id) {
    deleteImgIds.value.push(event.file?.id)
  }
  // uploadValidate()
}
const priceChange = debounce(500, priceChangeFun)
function priceChangeFun(productPrice: any) {
  // 先去掉逗号分隔符
  const price = deThousandSeparatFormat(productPrice)
  // 再插入分隔符
  formData.productPrice = thousandSeparatFormat(price)
}
// 发布成功回调
function successCalback() {
  infoFormRef?.value?.resetFields()
  infoFormRef?.value?.resetFields()
  const title = productId.value ? '保存成功' : '发布成功'
  uni.showToast({
    title,
    icon: 'success'
  })
  uni.switchTab({
    url: '/pages/index/index'
  })
}
// 文件上传存储
async function afterRead(event: any) {
  const photos = handleFile(event)
  formData.files = formData.files.concat(photos)
  if (formData.files.length) {
    infoFormRef.value.clearValidate('files')
    infoFormRef.value.clearValidate('oemCode')
  }
}
async function saveProduct() {
  const isAddPicture = formData.files.length && formData.files.some(item => !(item?.id))
  Promise.all([infoFormRef.value.validate()]).then(async (results) => {
    const [vaild1] = results
    const params: any = {
      name: formData.name,
      productPrice: deThousandSeparatFormat(formData.productPrice),
      oemCodeStr: oemCode.value.join(),
      supplierSkuId: formData.supplierSkuId,
      weight: formData.weight,
      currency: formData.currencyCode
    }
    // 编辑则加参数id、价格id、删除图片id
    if (productId.value) {
      params.id = productId.value
      params.priceId = currentRecord.value.priceInfoDtos[0].priceId
      if (deleteImgIds.value.length) {
        params.deleteImgIds = deleteImgIds.value.join()
      }
    }
    if (vaild1 === true) {
      // 保存商品信息，拿到id
      const { data } = productId.value ? await productManageSupUpdateProduct(params) : await productManageSupSaveProduct(params)
      if (data?.code === 200 && !isAddPicture) {
        successCalback()
      }
      if (data?.code !== 200 && data?.msg) {
        uni.showToast({
          title: data?.msg,
        })
        return
      }
      // 根据id单独调用上传图片接口
      if (isAddPicture) {
        const uploadParams = { id: '' }
        if (productId.value) {
          uploadParams.id = productId.value
        } else {
          uploadParams.id = data.data
        }
        const newFiles = formData.files.filter(e => !e.id) || []
        await Promise.all(newFiles.map(async (e) => {
          const promise = await uploadFilePromise(e.url, uploadParams)
          return promise
        })).then((results) => {
          const success = results.every(item => {
            item = JSON.parse(item)
            return item.code === 200
          })
          if (success) {
            successCalback()
          }
        }).catch((err: any) => {
          uni.showToast({
            title: '上传失败',
            icon: 'error'
          })
          console.error('上传失败:', err)
        })
      }
    }
  })
    .catch((error) => {
      console.error('保存失败:', error);
    })
}
const addProductSave = debounce(500, saveProduct)
async function getProductDetail() {
  const { data } = await productQueryProductDetailId({ id: productId.value })
  if (data?.code !== 200) return
  else {
    const result = data.data
    currentRecord.value = result
    formData.name = result.name
    formData.productPrice = thousandSeparatFormat(result.priceInfoDtos[0].productPrice)
    if (result.priceInfoDtos[0].currency) {
      formData.currency = result.priceInfoDtos[0].currency?.unitSymbol
      formData.currencyCode = result.priceInfoDtos[0].currency?.code
    } else {
      formData.currency = includeRMB.value ? '￥' : currencyList.value[0].unitSymbol
      formData.currencyCode = includeRMB.value ? 'CNY' : currencyList.value[0].code
    }
    formData.weight = result.weight || ''
    const oemArr = result.oemCodeList?.length && result.oemCodeList.map((item: any) => item.oemCode) || []
    formData.oemCode = oemArr.join()
    if (formData.oemCode.trim()) {
      oemCode.value = formData.oemCode.split(/[,，]/g)
    } else {
      oemCode.value = []
    }
    formData.supplierSkuId = result.supplierSkuId
    if (result?.fileInfos && result?.fileInfos?.length) {
      const arr: any = []
      result?.fileInfos.forEach((e) => {
        Object.assign(e, { url: e.fileUrl })
        arr.push(e)
      })
      if (arr.length > 3) arr.length = 3
      formData.files = arr
    }
  }
}
onLoad(async (options) => {
  if (options?.id) {
    productId.value = options?.id
    await getProductDetail()
    // 自定义导航栏
    uni.setNavigationBarTitle({
      title: options?.id ? '产品编辑' : '产品发布' // 页面标题为"自定义标题"
    });
  } else {
    formData.currency = includeRMB.value ? '￥' : currencyList.value[0].unitSymbol
    formData.currencyCode = includeRMB.value ? 'CNY' : currencyList.value[0].code
  }
})
</script>
<style scoped lang="scss">
.oem-box {
  box-sizing: border-box;
  min-height: 80rpx;
  border: 1px solid #D1D5DB;
  border-radius: 8rpx;
  vertical-align: middle;
  padding: 10rpx;
}
</style>
